#import "TileView.h"
#import "NetHackViewController.h"

#define TILE_SCALE 2
#define TS (TILE_SIZE * TILE_SCALE)

@implementation TileView

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
		UIImage *tilesImage = [UIImage imageNamed:@"nhtiles-flip.png"];
		tiles = CGImageRetain(tilesImage.CGImage);
		
		clipRect = CGRectMake(0, 0, TS, TS);
		imageRect = CGRectMake(0, 0,
			TILE_SCALE * CGImageGetWidth(tiles), TILE_SCALE * CGImageGetHeight(tiles));		
    }
    return self;
}

- (void)dealloc {
	CGImageRelease(tiles);
    [super dealloc];
}

- (void)drawRect:(CGRect)rect {	
	CGContextRef context = UIGraphicsGetCurrentContext();
	//! use `clearsContextBeforeDrawing` property instead.
	CGContextClearRect(context, rect);
	
	CGPoint center = self.center;
	
	int playerX = center.x - TS / 2;
	int tilesToLeft = playerX / TS + 1;
	int left = playerX - tilesToLeft * TS;
	int minCol = clipX - tilesToLeft;
	int tilesFromLeftToRight = tilesToLeft * 2 + 1;
	int maxCol = minCol + tilesFromLeftToRight;
	
	int playerY = center.y - TS / 2;
	int tilesAbove = playerY / TS + 1;
	int top = playerY - tilesAbove * TS;
	int minRow = clipY - tilesAbove;
	int tilesFromTopToBottom = tilesAbove * 2 + 1;
	int maxRow = minRow + tilesFromTopToBottom;
	
	for (int c = minCol; c < maxCol; ++c) {
		for (int r = minRow; r < maxRow; ++r) {
			int x = left + (c - minCol) * TS;
			int y = top + (r - minRow) * TS;
			
			clipRect.origin.x = x;
			clipRect.origin.y = y;
			
			int tileId = tileAt(c, r);
			if (tileId < 0) {
				continue;
			}
			int tileCol = tileId % TILES_PER_ROW;
			int tileRow = tileId / TILES_PER_ROW;
			
			imageRect.origin.x = x - tileCol * TS;
			imageRect.origin.y = y - tileRow * TS;
						
			CGContextSaveGState(context);
			CGContextClipToRect(context, clipRect);
			CGContextDrawImage(context, imageRect, tiles);
			CGContextRestoreGState(context);
		}
	}
}

@end
